<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>FFMPEG</title>
  </head>
  <body>
    <div>
      <h3>Upload a video to transcode to mp4 (x264) and play!</h3>
      <video id="output-video" controls></video><br />
      <input type="file" id="uploader" />

      <p id="message"></p>
    </div>

    <!-- <script src="./node_modules/coi-serviceworker/coi-serviceworker.min.js"></script> -->
    <script src="./node_modules/@ffmpeg/ffmpeg/dist/umd/ffmpeg.js"></script>
    <!-- <script src="./node_modules/@ffmpeg/core/dist/umd/ffmpeg-core.js"></script> -->
    <script src="./node_modules/@ffmpeg/util/dist/umd/index.js"></script>
    <script>
      const ffmpeg = new FFmpegWASM.FFmpeg();

      ffmpeg.on('log', ({ message }) => {
        console.log(message);
      });

      const baseURL = 'http://127.0.0.1:8888/node_modules/@ffmpeg/core/dist/umd'

      const transcode = async ({ target: { files } }) => {
        const message = document.getElementById('message');

        const { name } = files[0];

        message.innerHTML = 'Loading ffmpeg-core.js';

        await ffmpeg.load({
          coreURL: await FFmpegUtil.toBlobURL(`${baseURL}/ffmpeg-core.js`, 'text/javascript'),
          wasmURL: await FFmpegUtil.toBlobURL(`${baseURL}/ffmpeg-core.wasm`, 'application/wasm'),
        });


        await ffmpeg.writeFile('test.mp4', await FFmpegUtil.fetchFile(files[0]));

        message.innerHTML = 'Start transcoding';

        await ffmpeg.exec(['-i', 'test.mp4', 'output.mp4']);

        message.innerHTML = 'Complete transcoding';

        const data = await ffmpeg.readFile('output.mp4');

        const video = document.getElementById('output-video');

        video.src = URL.createObjectURL(
          new Blob([data.buffer], { type: 'video/mp4' })
        );
      };

      const elm = document.getElementById('uploader');

      elm.addEventListener('change', transcode);
    </script>
  </body>
</html>
